package com.we.wfc.system.dto;

import com.google.common.collect.Lists;
import com.we.wfc.common.utils.CommonUtil;
import com.we.wfc.common.utils.ConverterUtil;
import com.we.wfc.system.entity.Dict;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * 字典查询dto
 *
 * @author zhangby
 * @date 23/11/19 6:26 pm
 */
@Data
@Accessors(chain = true)
public class DictQueryDto {
    /**
     * 关键字
     */
    @ApiModelProperty("标签名")
    private String label;

    @ApiModelProperty("类型")
    private String type;

    @ApiModelProperty("父类id")
    private String parentId;

    private String keyword;

    /**
     * 设置查询条件
     */
    public Specification<Dict> buildQuery() {

        Specification<Dict> specification = (root, query, cb) -> {
            List<Predicate> predicateList = Lists.newArrayList();
            // 模糊查询
            CommonUtil.emptyStr(label).ifPresent(key ->
                    predicateList.add(cb.and(
                            cb.like(root.get("label").as(String.class), "%" + label + "%")
                    ))
            );
            CommonUtil.emptyStr(type).ifPresent(key ->
                    predicateList.add(cb.and(
                            cb.like(root.get("type").as(String.class), "%" + type + "%")
                    ))
            );
            CommonUtil.emptyStr(keyword).ifPresent(key ->
                    predicateList.add(
                            cb.or(
                                    cb.like(root.get("label").as(String.class), "%" + keyword + "%"),
                                    cb.like(root.get("value").as(String.class), "%" + keyword + "%"),
                                    cb.like(root.get("description").as(String.class), "%" + keyword + "%")
                            )
                    )
            );
            return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
        };

        return specification;
    }
}
